package com.tagtraum.perf.gcviewer;

import com.google.common.base.Predicate;

import javax.swing.DefaultListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class SectionsModel
  implements ListDataListener
{
  private static final WarningSeverityLevel NO_SEVERITY = null;
  private final DefaultListModel model;
  private Predicate<Section> filter;
  private DefaultListModel other;

  public SectionsModel()
  {
    this.model = new DefaultListModel();
  }

  public SectionsModel(SectionsModel other, Predicate<Section> filter) {
    this();
    this.filter = filter;
    this.other = other.getListModel();
    this.other.addListDataListener(this);
  }

  public void remove(int index) {
    this.model.remove(index);
  }

  public void addSection(String name) {
    this.model.addElement(new Section(this, name, NO_SEVERITY, false, false));
  }

  public void newGroup() {
    if (this.model.isEmpty()) {
      return;
    }
    Section lastSection = (Section)this.model.get(this.model.size() - 1);
    lastSection.setLastInGroup(true);
  }

  public void addSectionHeading(String name) {
    newGroup();
    this.model.addElement(new Section(this, name, NO_SEVERITY, true, false));
  }

  public void addAnalyticSection(String name, WarningSeverityLevel severity, boolean isOn) {
    this.model.addElement(new Section(this, name, severity, false, isOn));
  }

  public DefaultListModel getListModel() {
    return this.model;
  }

  boolean isLastSection(Section section) {
    int successorIndex = this.model.indexOf(section) + 1;
    return successorIndex == this.model.size();
  }

  public void contentsChanged(ListDataEvent event)
  {
  }

  public void intervalAdded(ListDataEvent event)
  {
    int index = event.getIndex0();
    Section section = (Section)this.other.get(index);
    if (this.filter.apply(section))
      this.model.addElement(section);
  }

  public void intervalRemoved(ListDataEvent event)
  {
  }
}